package com.stellar.pay.core.service.impl;

import com.stellar.pay.config.WxPayConfig;
import com.stellar.pay.core.service.IWxPayNativeService;
import com.stellar.pay.core.utils.IdempotentRequestChecker;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/4/5
 */
@Service
@AllArgsConstructor
@Slf4j
public class WxPayNativeServiceImpl implements IWxPayNativeService {

    private final WxPayConfig wxPayConfig;

    @Override
    public String nativePay(String outTradeNo, BigDecimal totalAmount, String description) {

        // 幂等检查 - 5分钟内相同outTradeNo的请求视为重复
        if (IdempotentRequestChecker.isDuplicateRequest(outTradeNo)) {
            log.warn("重复支付请求 | outTradeNo:{}", outTradeNo);
            throw new RuntimeException("重复支付请求，请勿重复提交");
        }

        Config config = new RSAPublicKeyConfig.Builder()
                .merchantId(wxPayConfig.getMchId())
                .privateKeyFromPath(wxPayConfig.getMchPrivateKeyPath())
                .publicKeyFromPath(wxPayConfig.getWxPublicKeyPath())
                .publicKeyId(wxPayConfig.getWxPublicKeyId())
                .merchantSerialNumber(wxPayConfig.getMchSerialNumber())
                .apiV3Key(wxPayConfig.getApiV3Key())
                .build();

        PrepayRequest prepayRequest = new PrepayRequest();
        prepayRequest.setAppid(wxPayConfig.getAppId());
        prepayRequest.setMchid(wxPayConfig.getMchId());
        prepayRequest.setOutTradeNo(outTradeNo);
        prepayRequest.setDescription(description);
        prepayRequest.setNotifyUrl(wxPayConfig.getNotifyUrl());

        Amount amount = new Amount();
        amount.setTotal(totalAmount.multiply(new BigDecimal("100")).intValue());
        amount.setCurrency("CNY");
        prepayRequest.setAmount(amount);

        NativePayService nativePayService = new NativePayService.Builder().config(config).build();
        PrepayResponse prepayResponse = nativePayService.prepay(prepayRequest);

        String codeUrl = prepayResponse.getCodeUrl();

        return codeUrl;
    }
}
